package com.hj.service.impl;

import java.io.File;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.alibaba.fastjson.JSONObject;
import com.hj.config.ConfigConstants;
import com.hj.model.CompressDescFile;
import com.hj.model.FileAttribute;
import com.hj.service.FilePreview;
import com.hj.util.FileUtils;
import com.hj.util.ZipReader;

/**
 * @author dehui dou
 * @date 2020/10/3 19:01
 * @description 压缩包文件处理类
 */
@Service
public class CompressFilePreviewImpl implements FilePreview {
    @Autowired
    private ZipReader zipReader;

    /**
     * @author dehui dou
     * @description 文件预览处理实现
     * @param model
     * @param fileAttribute
     * @return java.lang.String
     */
    @Override
    public String filePreviewHandle(Model model, FileAttribute fileAttribute) {
        String fileName = fileAttribute.getFileViewName();
        String fileRealName = fileAttribute.getFileRealName();
        String fileUniqueId = fileName.substring(0, fileName.lastIndexOf("."));
        String descFilePath = ConfigConstants.getFileDir() + fileUniqueId + File.separator + fileUniqueId + ".txt";
        String compressDirPath = ConfigConstants.getFileDir() + File.separator + fileUniqueId;
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
        File file = new File(compressDirPath);
        String fileTree = null;
        if (!file.exists()) {
            file.mkdirs();
            String filePath = ConfigConstants.getFileDir() + File.separator + fileName;
            CompressDescFile descFile = null;
            if ("zip".equalsIgnoreCase(extension) || "jar".equalsIgnoreCase(extension)
                || "gzip".equalsIgnoreCase(extension)) {
                descFile = zipReader.readZipFile(filePath, fileUniqueId, fileRealName);
            } else if ("rar".equalsIgnoreCase(extension)) {
                descFile = zipReader.unRar(filePath, fileUniqueId, fileRealName);
            } else if ("7z".equalsIgnoreCase(extension)) {
                descFile = zipReader.read7zFile(filePath, fileUniqueId, fileRealName);
            }
            fileTree = descFile.getFileTree();
            if (StringUtils.isNotEmpty(fileTree)) {
                FileUtils.savaStringToFile(JSONObject.toJSONString(descFile), descFilePath);
            }
        } else {
            String descFileStr = FileUtils.readFile(descFilePath);
            CompressDescFile descFile = JSONObject.parseObject(descFileStr, CompressDescFile.class);
            fileTree = descFile.getFileTree();
        }
        if (fileTree != null && !"null".equals(fileTree)) {
            model.addAttribute("fileTree", fileTree);
            return "compress";
        } else {
            model.addAttribute("msg", "压缩文件类型不受支持，尝试在压缩的时候选择RAR4格式");
            return "fileNotSupported";
        }
    }
}
